package arrays_and_matrices;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 按顺时针的方向，从外到里打印矩阵的值,下图的矩阵打印结果为 1,4,7,11,15,  19,22,24,30,  26,23,21,18,  10,3,2,  5,8,12,  16,17,  14,13,  6,9
 */
public class OrderPrint {
    public static void main(String[] args) {
        int[][] nums = new int[][]{
                {1,   4,  7, 11, 15},
                {2,   5,  8, 12, 19},
                {3,   6,  9, 16, 22},
                {10, 13, 14, 17, 24},
                {18, 21, 23, 26, 30}
        };
        OrderPrint orderPrint = new OrderPrint();
        orderPrint.orderPrint(nums);
    }

    public void orderPrint(int[][] arr) {
        List<Integer> list = new ArrayList<>();

        if (arr == null || arr.length == 0 || arr[0].length == 0) {
            return;
        }
        int r1 = 0, r2 = arr.length - 1, c1 = 0, c2 = arr[0].length - 1;
        while (r1 <= r2 && c1 <= c2) {
            for (int i = c1; i <= c2; i++) {
                list.add(arr[r1][i]);
            }

            for (int i = r1 + 1; i <= r2; i++) {
                list.add(arr[i][c2]);
            }

            if (r1 != r2) {
                for (int i = c2 - 1; i >= c1; i--) {
                    list.add(arr[r2][i]);
                }
            }

            if (c1 != c2) {
                for (int i = r2 - 1; i > r1; i--) {
                    list.add(arr[i][c1]);
                }
            }

            r1++;
            r2--;
            c1++;
            c2--;
        }

        String result = list.stream()
                .map(Object::toString)
                .collect(Collectors.joining(","));
        System.out.println(result);
    }
}
